#!/bin/bash
# TODO List Docker 局域网部署脚本

echo "🚀 TODO List Docker 局域网部署脚本"
echo "=================================="

# 检测操作系统并获取IP地址
get_lan_ip() {
    if command -v ip &> /dev/null; then
        # Linux
        ip route get 1 | awk '{print $7; exit}'
    elif command -v ifconfig &> /dev/null; then
        # macOS/Linux
        ifconfig | grep -E "inet.*broadcast" | awk '{print $2}' | head -1
    elif command -v ipconfig &> /dev/null; then
        # Windows (在Git Bash中)
        ipconfig | grep -A 1 "Wireless LAN adapter Wi-Fi:" | grep "IPv4" | awk '{print $14}' | head -1
    else
        echo "无法自动检测IP地址，请手动输入"
        read -p "请输入您的局域网IP地址: " lan_ip
        echo $lan_ip
    fi
}

# 获取局域网IP
LAN_IP=$(get_lan_ip)
if [ -z "$LAN_IP" ]; then
    read -p "请手动输入您的局域网IP地址: " LAN_IP
fi

echo "检测到的局域网IP地址: $LAN_IP"
read -p "确认使用此IP地址吗? (y/n): " confirm

if [ "$confirm" != "y" ] && [ "$confirm" != "Y" ]; then
    read -p "请输入正确的局域网IP地址: " LAN_IP
fi

# 检查是否存在 env.docker 文件
if [ ! -f "env.docker" ]; then
    if [ -f "env.docker.example" ]; then
        echo "复制环境变量模板..."
        cp env.docker.example env.docker
    else
        echo "❌ 未找到 env.docker.example 文件"
        exit 1
    fi
fi

# 更新环境变量文件
echo "📝 更新环境变量配置..."
sed -i.bak "s/YOUR_LAN_IP/$LAN_IP/g" env.docker

echo "✅ 环境变量配置完成"
echo ""

# 选择部署模式
echo "请选择部署模式："
echo "1. 完整部署 (包含 MySQL + Casdoor + TODO 应用)"
echo "2. Standalone 部署 (仅 TODO 应用，需要外部 Casdoor)"
read -p "请输入选择 (1 或 2): " mode

case $mode in
    1)
        echo "🚀 启动完整部署..."
        docker-compose --env-file env.docker up -d
        echo ""
        echo "✅ 部署完成！"
        echo "📱 访问地址："
        echo "   - TODO 应用: http://$LAN_IP:3000"
        echo "   - Casdoor 管理: http://$LAN_IP:8000"
        echo ""
        echo "📋 后续配置步骤："
        echo "   1. 等待 2-3 分钟让所有服务启动完成"
        echo "   2. 访问 http://$LAN_IP:8000 配置 Casdoor"
        echo "   3. 使用 admin/123 登录管理界面"
        echo "   4. 创建应用并配置回调URL: http://$LAN_IP:3000/api/auth/callback"
        ;;
    2)
        echo "🚀 启动 Standalone 部署..."
        docker-compose -f docker-compose.standalone.yml --env-file env.docker up -d
        echo ""
        echo "✅ 部署完成！"
        echo "📱 访问地址："
        echo "   - TODO 应用: http://$LAN_IP:3000"
        echo ""
        echo "📋 注意事项："
        echo "   1. 确保您的 Casdoor 服务正常运行"
        echo "   2. 确认 env.docker 中的 Casdoor 配置正确"
        ;;
    *)
        echo "❌ 无效选择，退出"
        exit 1
        ;;
esac

echo ""
echo "🔧 常用管理命令："
echo "   查看状态: docker-compose ps"
echo "   查看日志: docker-compose logs -f todo-app"
echo "   停止服务: docker-compose down"
echo "   重启服务: docker-compose restart todo-app" 